package cn.harry.cabinet.theme.manager

import android.app.Activity
import android.app.Application
import android.content.Context
import androidx.core.content.ContextCompat
import cn.harry.cabinet.R
import cn.harry.cabinet.model.entity.Configuration
import cn.harry.cabinet.repository.ConfigurationRepository
import cn.harry.cabinet.theme.constants.ThemeConstants

/**
 * 主题管理器 - 重构版本
 * 负责主题的切换、保存和应用
 * 
 * 特性：
 * - 统一的主题管理入口
 * - 支持SharedPreferences和数据库双重存储
 * - 兼容性状态栏更新
 * - 集成所有主题子系统
 */
object ThemeManager {
    
    private const val PREFS_NAME = "theme_preferences"
    private const val PREF_CURRENT_THEME = "current_theme"
    
    // 主题枚举
    enum class Theme(val key: String, val displayName: String) {
        CHINA_RED(ThemeConstants.ThemeTypes.CHINA_RED, "中国红"),
        VIBRANT_ORANGE(ThemeConstants.ThemeTypes.VIBRANT_ORANGE, "活力橙"),
        TECH_BLUE(ThemeConstants.ThemeTypes.TECH_BLUE, "科技蓝")
    }
    
    /**
     * 获取当前主题
     */
    fun getCurrentTheme(context: Context): Theme {
        val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        val themeKey = prefs.getString(PREF_CURRENT_THEME, ThemeConstants.Defaults.DEFAULT_THEME)
        return Theme.values().find { it.key == themeKey } ?: Theme.TECH_BLUE
    }
    
    /**
     * 设置主题
     */
    fun setTheme(context: Context, theme: Theme) {
        // 保存到SharedPreferences
        val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        prefs.edit().putString(PREF_CURRENT_THEME, theme.key).apply()
    }
    
    /**
     * 保存主题到数据库
     */
    suspend fun saveThemeToDatabase(context: Context, theme: Theme) {
        try {
            val app = when (context) {
                is Application -> context
                is Activity -> context.application
                else -> context.applicationContext as Application
            }
            val configRepo = ConfigurationRepository(app)
            
            val existing = configRepo.getByTypeAndKey(
                ThemeConstants.ConfigKeys.TYPE_THEME,
                ThemeConstants.ConfigKeys.KEY_CURRENT_THEME
            )
            
            if (existing == null) {
                configRepo.create(
                    Configuration(
                        type = ThemeConstants.ConfigKeys.TYPE_THEME,
                        key = ThemeConstants.ConfigKeys.KEY_CURRENT_THEME,
                        value = theme.key
                    )
                )
            } else {
                configRepo.update(existing.copy(value = theme.key, updateTime = java.util.Date()))
            }
            
        } catch (e: Exception) {

        }
    }
    
    /**
     * 从数据库加载主题设置
     */
    suspend fun loadThemeFromDatabase(context: Context): Theme {
        return try {
            val app = when (context) {
                is Application -> context
                is Activity -> context.application
                else -> context.applicationContext as Application
            }
            val configRepo = ConfigurationRepository(app)
            val config = configRepo.getByTypeAndKey(
                ThemeConstants.ConfigKeys.TYPE_THEME,
                ThemeConstants.ConfigKeys.KEY_CURRENT_THEME
            )
            
            config?.let { 
                Theme.values().find { theme -> theme.key == it.value } 
            }?.also { theme ->
            } ?: getCurrentTheme(context)
        } catch (e: Exception) {
            getCurrentTheme(context)
        }
    }
    
    /**
     * 应用主题颜色到Activity
     */
    fun applyTheme(activity: Activity, theme: Theme) {
        try {

            // 动态更新主题色彩
            updateDynamicColors(activity, theme)
            
            // 使用DynamicThemeUpdater进行实时主题更新
            cn.harry.cabinet.theme.updater.DynamicThemeUpdater.updateActivityTheme(activity, theme)
            
            // 应用导航菜单主题
            NavigationThemeManager.applyNavigationTheme(activity, theme)
            
            // 应用按钮主题到整个活动
            val rootView = activity.findViewById<android.view.View>(android.R.id.content)
            rootView?.let { 
                ButtonThemeManager.updateAllButtonsInView(it, theme, activity)
            }
            
            // 更新状态栏颜色 (使用兼容方式)
            updateStatusBarColor(activity, theme)
            
        } catch (e: Exception) {
        }
    }
    
    /**
     * 更新状态栏颜色（兼容方式）
     */
    private fun updateStatusBarColor(activity: Activity, theme: Theme) {
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                val themeColors = getThemeColors(theme)
                activity.window.statusBarColor = ContextCompat.getColor(activity, themeColors.primaryDark)
                
            }
        } catch (e: Exception) {
        }
    }
    
    /**
     * 动态更新主题颜色
     */
    private fun updateDynamicColors(context: Context, theme: Theme) {
        // 保存主题选择供下次启动使用
        val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        prefs.edit().putString(PREF_CURRENT_THEME, theme.key).apply()
        
    }
    
    /**
     * 获取主题的资源ID映射
     */
    fun getThemeResourceId(theme: Theme): Int {
        return R.style.Theme_SmartCabinet
    }
    
    /**
     * 获取主题对应的颜色资源ID映射
     */
    fun getThemeColors(theme: Theme): ThemeColors {
        return when (theme) {
            Theme.CHINA_RED -> ThemeColors(
                primary = ThemeConstants.ChinaRedColors.primaryColorRes,
                primaryDark = ThemeConstants.ChinaRedColors.primaryDarkColorRes,
                primaryLight = ThemeConstants.ChinaRedColors.primaryLightColorRes,
                secondary = ThemeConstants.ChinaRedColors.secondaryColorRes,
                accent = ThemeConstants.ChinaRedColors.accentColorRes,
                background = ThemeConstants.CommonColors.black,
                surface = R.color.dark_gray,
                surfaceVariant = ThemeConstants.CommonColors.gray,
                onPrimary = ThemeConstants.CommonColors.white,
                onSurface = ThemeConstants.CommonColors.white,
                onSurfaceVariant = ThemeConstants.CommonColors.white,
                divider = ThemeConstants.CommonColors.gray,
                glow = ThemeConstants.ChinaRedColors.primaryColorRes
            )
            
            Theme.VIBRANT_ORANGE -> ThemeColors(
                primary = ThemeConstants.VibrantOrangeColors.primaryColorRes,
                primaryDark = ThemeConstants.VibrantOrangeColors.primaryDarkColorRes,
                primaryLight = ThemeConstants.VibrantOrangeColors.primaryLightColorRes,
                secondary = ThemeConstants.VibrantOrangeColors.secondaryColorRes,
                accent = ThemeConstants.VibrantOrangeColors.accentColorRes,
                background = ThemeConstants.CommonColors.black,
                surface = R.color.dark_gray,
                surfaceVariant = ThemeConstants.CommonColors.gray,
                onPrimary = ThemeConstants.CommonColors.white,
                onSurface = ThemeConstants.CommonColors.white,
                onSurfaceVariant = ThemeConstants.CommonColors.white,
                divider = ThemeConstants.CommonColors.gray,
                glow = ThemeConstants.VibrantOrangeColors.primaryColorRes
            )
            
            Theme.TECH_BLUE -> ThemeColors(
                primary = ThemeConstants.TechBlueColors.primaryColorRes,
                primaryDark = ThemeConstants.TechBlueColors.primaryDarkColorRes,
                primaryLight = ThemeConstants.TechBlueColors.primaryLightColorRes,
                secondary = ThemeConstants.TechBlueColors.secondaryColorRes,
                accent = ThemeConstants.TechBlueColors.accentColorRes,
                background = ThemeConstants.CommonColors.black,
                surface = R.color.dark_gray,
                surfaceVariant = ThemeConstants.CommonColors.gray,
                onPrimary = ThemeConstants.CommonColors.white,
                onSurface = ThemeConstants.CommonColors.white,
                onSurfaceVariant = ThemeConstants.CommonColors.white,
                divider = ThemeConstants.CommonColors.gray,
                glow = ThemeConstants.TechBlueColors.primaryColorRes
            )
        }
    }
    
    /**
     * 主题颜色数据类
     */
    data class ThemeColors(
        val primary: Int,
        val primaryDark: Int,
        val primaryLight: Int,
        val secondary: Int,
        val accent: Int,
        val background: Int,
        val surface: Int,
        val surfaceVariant: Int,
        val onPrimary: Int,
        val onSurface: Int,
        val onSurfaceVariant: Int,
        val divider: Int,
        val glow: Int
    )
    
    /**
     * 主题切换动画
     */
    fun applyThemeWithAnimation(
        activity: Activity,
        fromTheme: Theme,
        toTheme: Theme,
        duration: Long = ThemeConstants.Defaults.THEME_ANIMATION_DURATION
    ) {
        // 应用新主题
        applyTheme(activity, toTheme)

    }
    
    /**
     * 检查主题是否需要更新
     */
    fun shouldUpdateTheme(context: Context, currentTheme: Theme): Boolean {
        val savedTheme = getCurrentTheme(context)
        return savedTheme != currentTheme
    }
    
    /**
     * 获取所有可用主题
     */
    fun getAllThemes(): Array<Theme> = Theme.values()
    
    /**
     * 根据字符串获取主题
     */
    fun getThemeByKey(key: String): Theme? {
        return Theme.values().find { it.key == key }
    }
}